#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: 即将拥有人鱼线的yjw
   @Time: 2023/11/17 15:13
   @File: bladeCaseOperate.py
   @desc:
"""
import json
import time
import uuid
from copy import copy

from BladeFerm.utils.OperationExcel import OperationExcel, ExcelVarles
from CommonScripts.APIRequest import APIRequset
from CommonScripts.Logs import logger

headers = {
        'Projectid': '289aa8a63edf4ca4a664743d6e5e9c5c',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        # 'Cookie':'gdp_user_id=c3c9daef-9860-4ba7-96ec-e46205798cd4; PS_DEVICEFEATURES=width:1280 height:720 pixelratio:1 touch:0 geolocation:1 websockets:1 webworkers:1 datepicker:1 dtpicker:1 timepicker:1 dnd:1 sessionstorage:1 localstorage:1 history:1 canvas:1 svg:1 postmessage:1 hc:0 maf:1; UqFC-yTtp36PRHYItgG2s3CcQP9YoNETJ4o_=v1Q9cyJQSDlNv; tenantId=default; UM_distinctid=18b46afb2625ea-000f0f7f6d423b-26031151-190140-18b46afb263c94; SHIROSESSIONID=26ab513d-dabf-4c30-aea0-b095512dd372; b3222f5ad5658c1a_gdp_cs1=gioenc-xdkv57416; b3222f5ad5658c1a_gdp_gio_id=gioenc-xdkv57416; b3222f5ad5658c1a_gdp_session_id=348f9811-9482-491b-b86b-01022fd4f55e; b3222f5ad5658c1a_gdp_session_id_348f9811-9482-491b-b86b-01022fd4f55e=true; b3222f5ad5658c1a_gdp_session_id_sent=348f9811-9482-491b-b86b-01022fd4f55e; projectId=0d45de36d752471eb885e407cb7b9878; vId=0d45de36d7; JSESSIONID=EA0D2A2F1C9751E9B092DF8DDA8A5D3E; '
        # 'Cookie':'gdp_user_id=c3c9daef-9860-4ba7-96ec-e46205798cd4; PS_DEVICEFEATURES=width:1280 height:720 pixelratio:1 touch:0 geolocation:1 websockets:1 webworkers:1 datepicker:1 dtpicker:1 timepicker:1 dnd:1 sessionstorage:1 localstorage:1 history:1 canvas:1 svg:1 postmessage:1 hc:0 maf:1; UM_distinctid=18b46afb2625ea-000f0f7f6d423b-26031151-190140-18b46afb263c94; b3222f5ad5658c1a_gdp_user_key=; UqFC-yTtp36PRHYItgG2s3CcQP9YoNETJ4o_=v1Q9cyJQSDlNv; SHIROSESSIONID=3772e85f-10e1-40af-a0a0-028d4fbb4612; PHPSESSID=517346f98323999fd2296a3f05b1ba8b; projectId=0d45de36d752471eb885e407cb7b9878; vId=0d45de36d7; b3222f5ad5658c1a_gdp_session_id=ee34c49a-4d83-4e7c-b945-c030bdf69e65; b3222f5ad5658c1a_gdp_session_id_ee34c49a-4d83-4e7c-b945-c030bdf69e65=true; b3222f5ad5658c1a_gdp_cs1=undefined; b3222f5ad5658c1a_gdp_gio_id=undefined; b3222f5ad5658c1a_gdp_esid=1106; b3222f5ad5658c1a_gdp_session_id_sent=ee34c49a-4d83-4e7c-b945-c030bdf69e65; b3222f5ad5658c1a_gdp_sequence_ids={%22globalKey%22:6833%2C%22VISIT%22:158%2C%22PAGE%22:956%2C%22CUSTOM%22:688%2C%22VIEW_CLICK%22:4839%2C%22VIEW_CHANGE%22:196}'
        #'Cookie':'gdp_user_id=c3c9daef-9860-4ba7-96ec-e46205798cd4; PS_DEVICEFEATURES=width:1280 height:720 pixelratio:1 touch:0 geolocation:1 websockets:1 webworkers:1 datepicker:1 dtpicker:1 timepicker:1 dnd:1 sessionstorage:1 localstorage:1 history:1 canvas:1 svg:1 postmessage:1 hc:0 maf:1; UM_distinctid=18b46afb2625ea-000f0f7f6d423b-26031151-190140-18b46afb263c94; b3222f5ad5658c1a_gdp_user_key=; SHIROSESSIONID=d23e607d-be72-46d3-9c87-c4d195854b68; UqFC-yTtp36PRHYItgG2s3CcQP9YoNETJ4o_=v1Q9cyJQSDlNv; projectId=289aa8a63edf4ca4a664743d6e5e9c5c; vId=289aa8a63e; b3222f5ad5658c1a_gdp_cs1=gioenc-xdkv57416; b3222f5ad5658c1a_gdp_gio_id=gioenc-xdkv57416; b3222f5ad5658c1a_gdp_session_id_sent=15f93fb0-7af2-4a42-93d0-e3856462d495; b3222f5ad5658c1a_gdp_session_id=0430a53c-ff2d-4d0a-a502-b5750c44f7d9; b3222f5ad5658c1a_gdp_session_id_0430a53c-ff2d-4d0a-a502-b5750c44f7d9=true; b3222f5ad5658c1a_gdp_esid=1113; b3222f5ad5658c1a_gdp_sequence_ids={%22globalKey%22:6854%2C%22VISIT%22:160%2C%22PAGE%22:961%2C%22CUSTOM%22:692%2C%22VIEW_CLICK%22:4849%2C%22VIEW_CHANGE%22:196}'
        # 'Cookie':'gdp_user_id=c3c9daef-9860-4ba7-96ec-e46205798cd4; PS_DEVICEFEATURES=width:1280 height:720 pixelratio:1 touch:0 geolocation:1 websockets:1 webworkers:1 datepicker:1 dtpicker:1 timepicker:1 dnd:1 sessionstorage:1 localstorage:1 history:1 canvas:1 svg:1 postmessage:1 hc:0 maf:1; UM_distinctid=18b46afb2625ea-000f0f7f6d423b-26031151-190140-18b46afb263c94; b3222f5ad5658c1a_gdp_user_key=; SHIROSESSIONID=d23e607d-be72-46d3-9c87-c4d195854b68; UqFC-yTtp36PRHYItgG2s3CcQP9YoNETJ4o_=v1Q9cyJQSDlNv; projectId=289aa8a63edf4ca4a664743d6e5e9c5c; vId=289aa8a63e; b3222f5ad5658c1a_gdp_session_id=6f529874-9b76-4c30-8ff2-62d70b5c136d; b3222f5ad5658c1a_gdp_session_id_6f529874-9b76-4c30-8ff2-62d70b5c136d=true; b3222f5ad5658c1a_gdp_cs1=undefined; b3222f5ad5658c1a_gdp_gio_id=undefined; b3222f5ad5658c1a_gdp_esid=1173; b3222f5ad5658c1a_gdp_session_id_sent=6f529874-9b76-4c30-8ff2-62d70b5c136d; b3222f5ad5658c1a_gdp_sequence_ids={%22globalKey%22:7353%2C%22VISIT%22:168%2C%22PAGE%22:1035%2C%22CUSTOM%22:766%2C%22VIEW_CLICK%22:5192%2C%22VIEW_CHANGE%22:196}'
        'Cookie':'gdp_user_id=c3c9daef-9860-4ba7-96ec-e46205798cd4; b3222f5ad5658c1a_gdp_user_key=; UqFC-yTtp36PRHYItgG2s3CcQP9YoNETJ4o_=v1Q9cyJQSDlNv; tenantId=default; b3222f5ad5658c1a_gdp_session_id=f2bb9dbe-e328-4691-9023-254d4179109d; b3222f5ad5658c1a_gdp_session_id_sent=f2bb9dbe-e328-4691-9023-254d4179109d; SHIROSESSIONID=c75da4c8-6261-4869-8208-0e92537b1277; b3222f5ad5658c1a_gdp_session_id_f2bb9dbe-e328-4691-9023-254d4179109d=true; ExpirePage=https://hr.hundsun.com/psp/ps/; PS_LOGINLIST=https://hr.hundsun.com/ps; PS_TOKEN=rQAAAAQDAgEBAAAAvAIAAAAAAAAsAAAABABTaGRyAk4AeQg4AC4AMQAwABT5fMI6M08Y8UP9hE0CBnxw1naSIm0AAAAFAFNkYXRhYXicJYtNCkBQGEWPnyxAtkEIL0MpGSiKkYmRiQ3o7c3iXM9365w7uJ8FwsD3PPnxcRdbTi5uKhpqcgzRzshKsggDGwcTMz2dXJWalBqn8se/F3rO1I1jLhZKTevWvEo2DWs=; PS_TokenSite=https://hr.hundsun.com/psp/ps/?psuat01-8000-PORTAL-PSJSESSIONID; SignOnDefault=; PS_LASTSITE=https://hr.hundsun.com/psp/ps/; ps_theme=node:HRMS portal:EMPLOYEE theme_id:DEFAULT_THEME_FLUID css:DEFAULT_THEME_FLUID accessibility:N formfactor:3 piamode:2; projectId=289aa8a63edf4ca4a664743d6e5e9c5c; vId=289aa8a63e; PS_TOKENEXPIRE=24_Apr_2024_00:30:01_GMT; JSESSIONID=C88D1E13F86789C7396A4566F065D81C; b3222f5ad5658c1a_gdp_gio_id=undefined; b3222f5ad5658c1a_gdp_cs1=undefined; b3222f5ad5658c1a_gdp_esid=5527; b3222f5ad5658c1a_gdp_sequence_ids={%22globalKey%22:38663%2C%22VISIT%22:753%2C%22PAGE%22:4404%2C%22CUSTOM%22:3552%2C%22VIEW_CLICK%22:29055%2C%22VIEW_CHANGE%22:900%2C%22FORM_SUBMIT%22:5}'

}

def addCase():
    #保存用例
    url ='https://blade.hundsun.com/api/v1/system/cache/saveTemplateForm.json'
    data = {
        'formName': 'addCase',
        'templateContent': '{"sourceurl": "business/testDesign/busiCaseTree", "updateTimeStr1": "", "saveType": "","templateId": "692218095cb8413b835bc35a0bb0a92e","nodePath": ".../02.客户信息管理/全量客户信息查询/功能操作/查询重置条件查询/通用", "caseName1": "新增测试用例","caseType1": "1", "casePrior1": "2", "caseDetailType1": "0", "caseLayer": "1","caseSideType1": "0"}',
        'templateName': 'default',
        'templateId': '692218095cb8413b835bc35a0bb0a92e'
    }
    httpClient = APIRequset(url, data, headers)
    res = httpClient.doPost()
    res_data = res.json()
    logger.info(f'{res_data}')

    #增加用例
    url = 'https://blade.hundsun.com/business/testDesign/caseStepCreateCase.json'
    data = {
        'sourceurl': 'business/testDesign/busiCaseDesign',
        'updateTimeStr1':'',
        'saveType':'',
        'templateId': '692218095cb8413b835bc35a0bb0a92e',
        'nodePath': '... /02.客户信息管理/全量客户信息查询/功能操作/查询重置条件查询/通用',
        'caseName1': '新增测试blade用例',
        'caseType1': '0',
        'casePrior1': '1',
        'caseDetailType1': '0',
        'caseLayer': '1',
        'caseSideType1':'0',
        'parCaseTreeId': '80959d17071b4d40b099db0623f94b2b',
        'caseId':'',
        'noReview': '3',
        'caseReviewBy':'',
        'caseName': '新增测试blade用例',
        'caseType': '1',
        'casePrior': '2',
        'caseDetailType': '0',
        'caseSideType': '0',
        'updateTimeStr':''
    }
    headers.update({'X-Requested-With':'XMLHttpRequest'})
    httpClient = APIRequset(url, data, headers)
    res = httpClient.doPost()
    res_data = res.json()
    logger.info(f'{res_data}')


def addCaseStep(caseId, precondition, stepDes, parameters, expect):

    '''
    给用例增加步骤
    '''
    stepTreeId = getCaseStepNode(caseId)
    node_list = getCaseStepNodeInfo(caseId, stepTreeId)
    stepTreeId = node_list['stepTreeId']
    userTreeId = node_list['userTreeId']
    # caseId="3c45191d20404104ba8887facb27d2d0"
    #通过caseTreeId,获取前置条件ID和其他步骤ID
    header = copy(headers)
    header.pop('Content-Type')
    url = 'https://blade.hundsun.com/api/v1/design/testDesign/getCaseStepNodes.json?caseId='+caseId+'&delFlag=1'
    httpClient = APIRequset(url, {}, header)
    res = httpClient.doPost()
    res_data = res.json()
    logger.info(f'getCaseStepNodes: {res_data}')
    logger.info(headers)
    stepList = res_data['data']['columns']
    first_key_step = ''
    remark_key_step = ''
    for step in stepList:
        if step['title'] == '前置条件':
            if 'user_key_' in step['key']:
                first_key_step = step['key']
        if step['title'] == '备注':
            if 'user_key_' in step['key']:
                remark_key_step = step['key']
    logger.info(f'stepTreeId：{stepTreeId}')
    logger.info(f'userTreeId：{userTreeId}')
    logger.info(f'first_key_step：{first_key_step}')
    logger.info(f'remark_key_step：{remark_key_step}')

    # 更新前置条件：
    headers.update({'Content-Type': 'application/json'})
    # headers.pop('Content-Type')
    url = 'https://blade.hundsun.com/api/v1/design/testDesign/updateCaseStepContents.json'
    data = {
        'stepTreeId': userTreeId,
        'treeContent': '{\"'+remark_key_step+'\":\"\",\"'+first_key_step+'\":\"'+precondition+'\"}'
        # {"user_key_fa35419724cc94bc052344c": "", "user_key_9112a413611d01d3dbf2474": "112<div>113</div><div>134</div>"}
    }
    logger.info(data)
    httpClient = APIRequset(url, json.dumps(data), headers)
    res = httpClient.doPost()
    res_data = res.json()
    logger.info(f'{res_data}')


    # 更新步骤描述stepDes 、输入数据inputData、预期结果Expect
    url ='https://blade.hundsun.com/api/v1/design/testDesign/insertCaseStep.json'
    data ={
        "treeName": '',
        "stepTreeId": stepTreeId,
        "treeNodeType": "1",
        "treeContent": '{\"stepName\":\"\",\"stepDes\":\"'+stepDes+'\",\"stepDesHtml\":\"'+stepDes+'\",\"Expect\":\"'+expect+'\",\"ExpectHtml\":\"'+expect+'\",\"inputData\":\"'+parameters+'\",\"inputDataHtml\":\"'+parameters+'\"}'
    }
    httpClient = APIRequset(url, json.dumps(data), headers)
    res = httpClient.doPost()
    res_data = res.json()
    logger.info(f'{res_data}')


# 获取用例单个步骤下前置条件、测试脚本、测试数据、检查和期望
def getCaseStepNodeInfo(caseId, stepTreeId):
    url = 'https://blade.hundsun.com/api/v1/design/testDesign/getCaseStepNodeInfo.json'
    data = {
            'caseId': caseId,
            'stepTreeId': stepTreeId,
            'delFlag': '1'
    }
    logger.info(data)
    header = copy(headers)
    header.update({'Accept':'application/json, text/plain, */*'})
    header.pop('Content-Type')
    logger.info(header)
    httpClient = APIRequset(url,data, header)
    res = httpClient.doPost()
    res_data = res.json()
    logger.info(f'res_data:{res_data}')
    return res_data['data']['data'][0]


# 获取路径下的用例
def getCaseDesignTreeData(treeParentId=None):
    url = 'https://blade.hundsun.com/business/testDesign/getCaseDesignTreeData.json'
    data = {
        'sourceurl': 'business/testDesign/busiCaseTree',
        'caseName': '',
        'titleName': '',
        'searchType': 'case,var,sql,data',
        'caseType': '',
        'casePrior': '',
        'caseSideType': '',
        'keyword': '',
        'caseState': '',
        'caseHeaders': '',
        'fieldToSearch': '',
        'variableName': '',
        'sqlName': '',
        'dataName': '',
        'treeParentId': 'de28f12c1373401c8e2287fa96429be9'
    }
    if treeParentId:
        data.update({'treeParentId':treeParentId})
    httpClient = APIRequset(url, data, headers)
    res = httpClient.doPost()
    # logger.info(res.text)
    res_data = res.json()
    return res_data


def getCaseId(caseDir):
    caseDirList = caseDir.split('/')
    caseIdList = {}
    id = ''
    for i in range(len(caseDirList)):
        if i < len(caseDirList) - 1:
            if caseDirList[i] == '功能案例库':
                res_data = getCaseDesignTreeData()
                # logger.info(f'{res_data}')
            else:
                res_data = getCaseDesignTreeData(id)
                # logger.info(f'{res_data}')
            for resd in res_data:
                if resd['name'] == caseDirList[i+1]:
                    id = resd['id']

        else:
            res_data = getCaseDesignTreeData(id)
            # logger.info(f'{res_data}')
            for j in res_data:
                if j['type'] == 2:
                    caseIdList.update({j['name']: j['caseId']})
                elif j['type'] == 1:
                    name1 = j['name']
                    res_data1 = getCaseDesignTreeData(j['id'])
                    for k in res_data1:
                        caseIdList.update({name1+'-'+k['name']: k['caseId']})
    logger.info(f'{caseIdList}')
    for j in caseIdList.keys():
        print(j)
    return caseIdList


# 获取用例步骤：
def getCaseStepNode(caseId, index=1):
    header = copy(headers)
    header.update({'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'})
    # url = 'https://blade.hundsun.com/api/v1/design/testDesign/getAllCaseInfoById.json'
    # data = {
    #     'caseId': caseId,
    # }
    # httpClient = APIRequset(url, data, header)
    # res = httpClient.doPost()
    # res_data = res.json()
    # caseTreeId = res_data['data']['bCase']['caseTreeId']
    #
    # url = 'https://blade.hundsun.com/business/testDesign/getTreeNodeInfo.json'
    # data = {
    #     'caseTreeId': caseTreeId,
    # }
    # httpClient = APIRequset(url, data, header)
    # httpClient.doPost()
    #
    # url = 'https://blade.hundsun.com/api/v1/design/testDesign/getTestCaseStepsHeader.json'
    # data = {
    #     'caseId': caseId,
    # }
    # httpClient = APIRequset(url, data, header)
    # httpClient.doPost()
    #
    # # 获取用例步骤：
    url = 'https://blade.hundsun.com/api/v1/design/testDesign/getCaseStepNodes.json'
    data = {
        'caseId': caseId,
        'delFlag': '1'
    }
    httpClient = APIRequset(url, data, header)
    res = httpClient.doPost()
    res_data = res.json()
    if res_data['data']['data']:
        logger.info('stepTreeId存在')
        rows = res_data['data']['data']
        if len(rows) > 1:
            noneScriptId = 'a487aab17cca48ccacd8f2235d3b9701'  # UI自动化空脚本 的ID
            for i in range(1, len(rows)):
                stepTreeId = rows[i].get('stepTreeId')
                stepData_1 = getCaseStepNodeInfo(caseId, stepTreeId)
                scriptTreeId = stepData_1['scriptTreeId']  # 步骤脚本ID
                relationScrip(caseId, stepTreeId, scriptTreeId, scriptType='common_none')
    else:
        addCaseStepNodes(caseId)
        time.sleep(1)
        httpClient = APIRequset(url, data, header)
        res = httpClient.doPost()
        res_data = res.json()
    stepTreeId = res_data['data']['data'][index-1]['stepTreeId']
    # logger.info(f'{res_data}')
    logger.info(f'{stepTreeId}')
    return stepTreeId


# 用例绑定脚本
def insertCaseStepContent(caseId, ScriptName=None):
    # caseId = '9cc51c1dac1e44b1b841e60e983a0d49'
    # 获取用例步骤：
    stepTreeId = getCaseStepNode(caseId)
    logger.info(f'insertCaseStepContent stepTreeId: {stepTreeId}')
    # 获取步骤脚本ID
    # stepData = getCaseStepNodeInfo(caseId,stepTreeId='')
    stepData_1 = getCaseStepNodeInfo(caseId, stepTreeId)
    # 步骤脚本ID
    scriptTreeId = stepData_1['scriptTreeId']
    # checkTreeId = stepData['checkTreeId'] #步骤检查ID
    # preTreeId = stepData['preTreeId'] #步骤前置条件ID
    # dataTreeId = stepData['dataTreeId'] #步骤数据ID
    # #获取脚本ID
    # url = 'https://blade.hundsun.com/business/scriptDesign/getScriptList.json'
    # data = {
    #     'ourceurl': 'business/testDesign/busiCaseTree',
    #     'caseId':caseId,
    #     'caseTreeId':'',
    #     'scriptSelectedId':'',
    #     'word':ScriptName,
    #     'pageNo':1,
    #     'pageSize': 10
    #     # {"user_key_fa35419724cc94bc052344c": "", "user_key_9112a413611d01d3dbf2474": "112<div>113</div><div>134</div>"}
    # }
    # httpClient = APIRequset(url, data, headers)
    # res = httpClient.doPost()
    # res_data = res.json()
    # # logger.info(f'{res_data}')
    # rows = res_data['rows']
    # elementId = ''
    # scriptContent = ''
    # scriptType = ''
    # for row in rows:
    #     if row['scriptName'] == ScriptName:
    #         elementId = row['scriptId']
    #         scriptContent = row['scriptContent']
    #         scriptType = row['scriptType']

    # 通过用例ID和脚本ID实现绑定
    relationScrip(caseId, stepTreeId, scriptTreeId)


def relationScrip(caseId, stepTreeId, scriptTreeId, scriptType='common_query'):
    """
    ScriptName = '通用查询UI脚本'
    elementId = 'a34a3d98590b4769adee24b81c12d381'
    scriptContent = "python|testDataCase.AmlAutoTest,search_info,web应用,100,"
    scriptType = '47'
    """
    # 通过用例ID和脚本ID实现绑定
    url = 'https://blade.hundsun.com/api/v1/design/testDesign/insertCaseStepContent.json'
    scripts = {'common_query': {"id": "a34a3d98590b4769adee24b81c12d381",
                                "type": "47",
                                "content": "通用查询UI脚本",
                                "contentDetail": "python|testDataCase.AmlAutoTest,search_info,web应用,100,"
                                },
               'common_none': {"id": "a487aab17cca48ccacd8f2235d3b9701",
                               "type": "3",
                               "content": "UI自动化空脚本",
                               "contentDetail": "dbInit|,"
                               }
               }
    script_content = scripts.get(scriptType)
    elementId = script_content.get('id')
    data = {
        'caseId': caseId,
        'elementId': elementId,
        'stepId': stepTreeId,
        'stepTreeId': scriptTreeId,
        'treeContent': json.dumps(script_content),
        # 'treeContent': '{\"id\":\"a34a3d98590b4769adee24b81c12d381\",\"type\":\"47\",\"content\":\"通用查询UI脚本\",\"contentDetail\":\"python|testDataCase.AmlAutoTest,search_info,web应用,100,\"}',
        'treeNodeType': "3"
    }
    logger.info(data)
    headers.update({'Content-Type': 'application/json'})
    data1 = json.dumps(data, ensure_ascii=False)
    logger.info(data1.encode("utf-8"))
    httpClient = APIRequset(url, data1.encode("utf-8"), headers)
    res = httpClient.doPost()
    res_data = res.json()
    logger.info(f'{res_data}')


#用例绑定测试数据
# def updateCaseStepContent(caseId,caseName,fileName):
#
#
#     url = 'https://blade.hundsun.com/api/v1/design/testDesign/updateCaseStepContents.json'
#     data = {
#         'caseId' : '9cc51c1dac1e44b1b841e60e983a0d49',
#         'delFlag':'1',
#         'stepId':'f57f3a4d7ac77e6ee390186a658e2a23',
#         'stepTreeId':"b4fbb27dc97e5fd2d0bbdf28a4398e6c",
#         # 'treeContent': '{\"id\":\"''\",\"dataChoseRow\":\"' + row_2 + ',\",\"caseId\":\"' + caseId + '\",\"content\":\"' + fileName + '\"}'
#         'treeContent':'{\"id\":\"\",\"dataChoseRow\":\"'+row_2+',\",\"caseId\":\"'+caseId+'\",\"content\":\"'+fileName+'\",\"dataArrContent\":\"[{\\\"Sheet0\\\":[[\\\"'+row_0+'\\\",\\\"序号\\\",\\\"期望\\\",\\\"caseId\\\",\\\"caseName\\\"],[\\\"'+row_1+'\\\",\\\"参数说明\\\",\\\"\\\"],[\\\"c819fa550e9f2a971d9149295a1be36b\\\",null,null,\\\"111\\\",\\\"222\\\"],[\\\"2d4fc4f99fb06a6b09ca189379592459\\\",null,null,\\\"333\\\",\\\"4444\\\"],[\\\"68f31c141633d3609af4375ddf49332a\\\",null,null,\\\"5555\\\",\\\"66666\\\"],[\\\"a11f0f0b600b86446942f782a4b1fb6e\\\",null,null,\\\"777\\\",\\\"8888\\\"],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]]}]\"}'
#     }
#     headers.update({'Content-Type': 'application/json'})
#     httpClient = APIRequset(url, json.dumps(data), headers)
#     res = httpClient.doPost()
#     res_data = res.json()
#     logger.info(f'{res_data}')


# 用例写入数据
def insertCaseData(caseId, xlsxName, sheetName, caseName):
    stepTreeId = getCaseStepNode(caseId)
    logger.info(f'{stepTreeId}')
    stepData_1 = getCaseStepNodeInfo(caseId, stepTreeId)
    dataRow = stepData_1['dataNode'][0]
    logger.info(dataRow)
    dataTreeId = stepData_1['dataTreeId']
    logger.info(dataTreeId)
    dataChoseRow = dataRow['dataChoseRow']
    if dataChoseRow:
        logger.info(dataChoseRow)
    else:
        dataChoseRow = getUuid_32()
    sheet_0 = dataRow['dataArrContent']
    logger.info(sheet_0)
    logger.info(type(sheet_0))
    url = 'https://blade.hundsun.com/api/v1/design/testDesign/updateCaseStepContents.json'
    treeContent = {"id": "",
                   "dataChoseRow": dataChoseRow.rstrip(','),
                   "caseId": caseId,
                   "dataArrContent": [
                       {"Sheet0": [
                           ["", "序号", "期望", "xlsxName", "sheetName", "caseName", "", "", "", ""],
                           ["", "参数说明", "", "", "", "", "", "", "", ""],
                           [dataChoseRow.rstrip(','), "No.1", "flag=true", xlsxName, sheetName, caseName, "", "", "", ""]
                       ]}
                   ]}
    data = {
        'release': False,
        'treeNodeType': '4',
        'caseId': caseId,
        'delFlag': '1',
        'stepId': stepTreeId,
        'stepTreeId': dataTreeId,
        'treeContent': json.dumps(treeContent)
        # 'treeContent': '{\"id\":\"\",\"dataChoseRow\":\"'+dataChoseRow+',\",\"caseId\":\"'+caseId+'\",\"dataArrContent\":[{\"Sheet0\":[[\"\",\"序号\",\"期望\",\"xlsxName\",\"sheetName\",\"caseName\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],[\"\",\"参数说明\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],[\"'+dataChoseRow+'\",\"\",\"flag=true\",\"'+xlsxName+'\",\"'+sheetName+'\",\"'+caseName+'\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]]}]}'
    }
    data1 = json.dumps(data, ensure_ascii=False)
    logger.info(data1)
    headers.update({'Content-Type': 'application/json'})
    httpClient = APIRequset(url, data1.encode("utf-8"), headers)
    res = httpClient.doPost()
    res_data = res.json()
    logger.info(f'{res_data}')


def getCaseIdList(caseDir):
    '''
    获取节点下全部用例id,用于上传用例
    '''
    treeParentId = 'd9486d31bea042108b34d7289330fe8e'
    caseDirList = caseDir.split('/')
    caseIdList = {}
    id = ''
    for i in range(len(caseDirList)):
        if i < len(caseDirList) - 1:
            if caseDirList[i] == '功能案例库':
                res_data = getCaseDesignTreeData()
                # logger.info(f'{res_data}')
            else:
                res_data = getCaseDesignTreeData(id)
                # logger.info(f'{res_data}')
            for resd in res_data:
                if resd['name'] == caseDirList[i+1]:
                    id = resd['id']
        else:
            res_data = getCaseDesignTreeData(id)
            # logger.info(f'{res_data}')
            for j in res_data:
                if j['type'] == 2:
                    caseIdList.update({j['name']: j['caseId']})
                elif j['type'] == 1:
                    name1 = j['name']
                    res_data1 = getCaseDesignTreeData(j['id'])
                    for k in res_data1:
                        caseIdList.update({name1+'-'+k['name']: k['caseId']})
    logger.info(f'{caseIdList}')
    return caseIdList


def updateCaseList(caseDir, xlsxName, sheetName, path='C:\\Users\\yejw46507\\Downloads\\客户信息管理.xlsx'):  #E:\\UI自动化\\Project\\金融反洗钱项目\\web应用
    caseIdList = getCaseIdList(caseDir)
    datas = OperationExcel(xlsxName, sheetName, path).readExcelDatas()
    for data in datas:
        logger.info(f"case row : {data}")
        caseName = data[ExcelVarles.case_name]
        stepDes = data[ExcelVarles.case_describe]
        inputData = data[ExcelVarles.case_data]
        expect = data[ExcelVarles.case_result]
        case_before = data[ExcelVarles.case_before]
        caseId = caseIdList.get(caseName)
        if caseId:
            addCaseStep(caseId, case_before, stepDes, inputData, expect)
            insertCaseStepContent(caseId)
            insertCaseData(caseId, xlsxName, sheetName, caseName)
            time.sleep(0.5)


def getUuid_32():
    temp = uuid.uuid4()
    return temp.hex


def addCaseStepNodes(caseId):
    url = 'https://blade.hundsun.com/api/v1/design/testDesign/addCaseStepNodes.json'
    case_node = {"caseId": caseId,
                 "treeOrder": 1,
                 "stepName": "",
                 "stepDes": "",
                 "stepDesHtml": "",
                 "stepTreeId": getUuid_32(),
                 "preTreeId": getUuid_32(),
                 "preTreeDefaultId": getUuid_32(),
                 "scriptTreeId": getUuid_32(),
                 "scriptTreeDefaultId": getUuid_32(),
                 "dataTreeId": getUuid_32(),
                 "dataTreeDefaultId": getUuid_32(),
                 "checkTreeId": getUuid_32(),
                 "checkTreeDefaultId":getUuid_32(),
                 "userTreeId": getUuid_32(),
                 "userTreeDefaultId": getUuid_32()
                }
    default_value = {"user_key_9112a413611d01d3dbf2474":"","stepDes":"","inputData":"","Expect":"","user_key_fa35419724cc94bc052344c":"","action":""}
    data = {
        'caseNodes': json.dumps(case_node),
        'defaultValues': json.dumps(default_value)
    }
    print(json.dumps(data))
    header = copy(headers)
    header.update({'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'})
    header.pop('Content-Type')
    httpClient = APIRequset(url, data, header)
    res = httpClient.doPost()
    res_data = res.json()
    logger.info(res_data)


if __name__ == '__main__':
    # addCase()
    # addCaseStep()
    # caseDir = '功能案例库/02.客户信息管理/客户信息查询/交易流水查询/功能操作/查询重置条件查询/通用'
    # caseDir = '功能案例库/02.客户信息管理/菜单/06交易流水查询/交易申请/功能操作/查询重置/01.通用'
    # caseDir = '功能案例库/04.名单管理/菜单/01名单命中客户管理/查询'
    # caseDir = '功能案例库/02.客户信息管理/菜单/03机构户信息查询/功能操作/查询重置条件查询/通用'
    # caseDir = '功能案例库/02.客户信息管理/菜单/01全量客户信息查询/功能操作/查询重置条件查询/通用'
    # caseDir = '功能案例库/02.客户信息管理/菜单/02个人信息查询/功能操作/查询重置条件查询/通用'
    # caseDir = '功能案例库/02.客户信息管理/菜单/06交易流水查询/账户申请确认/功能操作/查询重置/01.通用'
    # caseDir = '功能案例库/02.客户信息管理/菜单/07客户风险信息报备/查询'
    # caseDir = '功能案例库/02.客户信息管理/菜单/08销售商信息管理/查询'
    # caseDir = '功能案例库/02.客户信息管理/菜单/09资产管理人/页面按钮/查询重置'
    # caseDir = '功能案例库/03.客户风险评估/菜单/01风险等级查询/功能操作/查询重置/通用'
    # caseDir = '功能案例库/03.客户风险评估/菜单/04客户评级流程查询/功能操作/查询重置'
    # caseDir = '功能案例库/05企业日志查询.可疑交易管理/菜单/01可疑交易查询/查询'
    # caseDir = '功能案例库/02.客户信息管理/菜单/10投顾客户管理/查询'
    # caseDir = '功能案例库/05企业日志查询.可疑交易管理/菜单/06可疑交易复核/查询'
    # caseDir = '功能案例库/08.客户合并管理/菜单/01客户合并场景管理/查询'
    # caseDir = '功能案例库/08.客户合并管理/菜单/02疑似同一客户管理/查询'
    # caseDir = '功能案例库/08.客户合并管理/菜单/03合并客户管理/查询'
    # caseDir = '功能案例库/02.客户信息管理/菜单/06交易流水查询/交易申请/功能操作/查询重置/01.通用'
    # caseDir = '功能案例库/07.产品风险评估/菜单/01产品风险评估查询/查询'
    # caseDir = '功能案例库/07.产品风险评估/菜单/02产品历史评估查询/查询'
    # caseDir = '功能案例库/02.客户信息管理/菜单/05受益所有人信息查询/功能操作/查询重置条件查询/通用'
    # caseDir = '功能案例库/08.客户合并管理/菜单/03合并客户管理/查询'
    caseDir = '功能案例库/02.客户信息管理/菜单/03机构户信息查询/功能操作/查询重置条件查询/通用'
    xlsxName = '客户信息管理'
    sheetName = '机构户信息查询'
    # login_info = {'username': "yejw46507", 'password': "", 'getToken': False, 'isClose': True,
    #               'jira_url': 'https://hs-cas.hundsun.com/cas/login?service=https://blade.hundsun.com/system/shiro-cas', 'project': "金融反洗钱项目"
    #               }
    # cookie = get_jsession(login_info)
    # headers.update({"Cookie": cookie})
    # caseId = '9cc51c1dac1e44b1b841e60e983a0d49'
    # insertCaseData(caseId)
    updateCaseList(caseDir, xlsxName, sheetName)
    # getCaseId(caseDir)
    # ScriptName = '01.录制登录脚本'
    # insertCaseStepContent('',ScriptName)
    # getCaseStepNodeInfo('', '')
    # caseId = '9cc51c1dac1e44b1b841e60e983a0d49'
    # # caseName = '01.默认查询条件查询'
    # caseName = '8888'
    # fileName = '机构户信息管理'
    # updateCaseStepContent(caseId,caseName,fileName)
    # caseId = 'a3f3118078f54bc7a171e0a9422c27c1'
    # # # stepTreeId = 'f57f3a4d7ac77e6ee390186a658e2a23'
    # getCaseStepNode(caseId)

    # getCaseStepNodeInfo(caseId, stepTreeId)